package com.dwxt.community.admin.service;

import com.alipay.api.domain.UserVo;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.ExcelUtils;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.community.dao.UserMapper;
import com.dwxt.community.entity.Community;
import com.dwxt.community.entity.IntegralRecord;
import com.dwxt.community.entity.User;
import com.dwxt.community.entity.UserExample;
import com.dwxt.community.entity.vo.TrashIntegralRecoadVo;
import com.dwxt.community.entity.vo.UserVO;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceAdmin {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommunityServiceAdmin communityServiceAdmin;

    @Autowired
    private IntegralRecordServiceAdmin integralRecordServiceAdmin;

    @Autowired
    private TrashServiceAdmin trashServiceAdmin;

    public BaseResult selectUserList(User user) {
        UserExample example = new UserExample();
        example.setOrderByClause("create_time desc");
        UserExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(user.getPhone())) {
            criteria.andPhoneEqualTo(user.getPhone());
        }
        if (StringUtils.isNotBlank(user.getUsername())) {
            criteria.andUsernameLike("%" + user.getUsername() + "%");
        }
        if (user.getIsHouseHead() != null) {
            criteria.andIsHouseHeadEqualTo(user.getIsHouseHead());
        }
        if (user.getIsNameAuthentication() != null) {
            criteria.andIsNameAuthenticationEqualTo(user.getIsNameAuthentication());
        }
        List<User> userList = userMapper.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo(userList);
        List<User> collect = userList.stream().map(u -> {
            UserVO userVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(u), UserVO.class);
            if (u.getIsHouseHead() == YesOrNo.NO) {
                User owner = userMapper.selectHouseOwnerByUserId(u.getId());
                if (owner != null) {
                    userVO.setHeadUsername(owner.getUsername());
                }
            } else {
                userVO.setHeadUsername(userVO.getUsername());
            }
            return userVO;
        }).collect(Collectors.toList());
        pageInfo.setList(collect);
        return BaseResult.ok(pageInfo);
    }

    public PageInfo<User> selectDemonstrationUserList(Integer pageNum, Integer pageSize, UserVO userVo) {
        if (userVo.getOrderType() == null || userVo.getOrderType() == 1) {
            return getDefaultUserPageInfo(pageNum, pageSize, userVo);
        } else if (userVo.getOrderType() == 2) {
            //那累计投放积分排序
            PageHelper.startPage(pageNum, pageSize);
            List<User> userList = userMapper.getTotalTrashIntegralUserPageInfo(userVo);
            PageInfo<User> pageInfo = new PageInfo<>(userList);
            List<User> userVOList = userList.stream().map(user -> {
                UserVO userVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(user), UserVO.class);
                Community community = communityServiceAdmin.selectById(userVO.getCommunityId());
                userVO.setStreet(community.getStreet());
                Long trashCount = trashServiceAdmin.countTrash(userVO.getId());
                userVO.setTrashCount(trashCount.intValue());
                return userVO;
            }).collect(Collectors.toList());

            pageInfo.setList(userVOList);
            return pageInfo;
        } else if (userVo.getOrderType() == 3) {
            //那累计投放积分排序
            PageHelper.startPage(pageNum, pageSize);
            List<User> userList = userMapper.getTrashCountUserPageInfo(userVo);
            PageInfo<User> pageInfo = new PageInfo<>(userList);
            List<User> userVOList = userList.stream().map(user -> {
                UserVO userVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(user), UserVO.class);
                Community community = communityServiceAdmin.selectById(userVO.getCommunityId());
                userVO.setStreet(community.getStreet());
                Integer totalTrashIntegral = integralRecordServiceAdmin.sumTrash(userVO.getId());
                userVO.setTotalTrashIntegral(totalTrashIntegral);
                return userVO;
            }).collect(Collectors.toList());
            pageInfo.setList(userVOList);
            return pageInfo;
        } else {
            throw new RuntimeException();
        }

    }

    private PageInfo<User> getDefaultUserPageInfo(Integer pageNum, Integer pageSize, UserVO userVo) {
        List<Community> communityList = communityServiceAdmin.selectDemonstrationCommunityList(userVo.getStreet());
        List<Integer> collect = communityList.stream().map(community -> community.getId()).collect(Collectors.toList());
        UserExample example = new UserExample();
        if (userVo.getOrderType() != null && userVo.getOrderType() == 1) {
            example.setOrderByClause("integral " + userVo.getSequence());
        }
        UserExample.Criteria criteria = example.createCriteria();
        if (collect.size() > 0) {
            criteria.andCommunityIdIn(collect);
        } else {
            criteria.andCommunityIdEqualTo(0);
        }
        if (StringUtils.isNotBlank(userVo.getCommunityName())) {
            criteria.andCommunityNameEqualTo(userVo.getCommunityName());
        }
        if (StringUtils.isNotBlank(userVo.getHouseNumber())) {
            criteria.andHouseNumberEqualTo(userVo.getHouseNumber());
        }

        if (StringUtils.isNotBlank(userVo.getUsername())) {
            criteria.andUsernameLike("%" + userVo.getUsername() + "%");
        }
        if (userVo.getIsOfficer() != null) {
            criteria.andIsOfficerEqualTo(userVo.getIsOfficer());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo<>(userList);

        List<User> userVOList = userList.stream().map(user -> {
            UserVO userVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(user), UserVO.class);
            Community community = communityServiceAdmin.selectById(userVO.getCommunityId());
            userVO.setStreet(community.getStreet());

            Integer totalTrashIntegral = integralRecordServiceAdmin.sumTrash(userVO.getId());
            Long trashCount = trashServiceAdmin.countTrash(userVO.getId());

            userVO.setTotalTrashIntegral(totalTrashIntegral);
            userVO.setTrashCount(trashCount.intValue());
            return userVO;
        }).collect(Collectors.toList());

        pageInfo.setList(userVOList);
        return pageInfo;
    }

    public void updateUser(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void recordExport(HttpServletResponse response, UserVO userVo) {
        List<UserVO> list = selectAll(userVo);
        //List<TrashIntegralRecoadVo> list = trashIntegralRecoadMapper.selectAll(trashIntegralRecoad);
        if (ObjectUtils.isNotEmpty(list)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //excel标题
            String[] title = {"街道", "小区", "门牌号", "用户名", "身份证号码", "户主/家人", "累计投放积分", "当前积分", "投放次数", "工作单位", "是否公务员"};

            //excel文件名
            String fileName = "投递用户记录表" + System.currentTimeMillis() + ".xls";

            //sheet名
            String sheetName = "投递用户记录表";
            String[][] content = new String[list.size()][11];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                UserVO userVO = list.get(i);
                content[i][0] = userVO.getStreet();
                content[i][1] = userVO.getCommunityName();
                content[i][2] = userVO.getHouseNumber();
                content[i][3] = userVO.getUsername();
                content[i][4] = userVO.getIdentityCard();
                content[i][5] = userVO.getIsHouseHead() == YesOrNo.YES ? "户主" : "家人";
                Integer totalTrashIntegral = userVO.getTotalTrashIntegral();
                content[i][6] = totalTrashIntegral == null ? "0" : totalTrashIntegral.toString();
                Integer integral = userVO.getIntegral();
                content[i][7] = integral == null ? "0" : integral.toString();
                Integer trashCount = userVO.getTrashCount();
                content[i][8] = trashCount == null ? "0" : trashCount.toString();
                content[i][9] = userVO.getWorkDepartment();
                Integer isOfficer = userVO.getIsOfficer();
                content[i][10] = isOfficer == null ? "" : (isOfficer == YesOrNo.YES ? "是" : "否");
            }

            //创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
            //响应到客户端
            try {
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private List<UserVO> selectAll(UserVO userVo) {
        List<Community> communityList = communityServiceAdmin.selectDemonstrationCommunityList(userVo.getStreet());
        List<Integer> collect = communityList.stream().map(community -> community.getId()).collect(Collectors.toList());
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (collect.size() > 0) {
            criteria.andCommunityIdIn(collect);
        } else {
            criteria.andCommunityIdEqualTo(0);
        }
        if (StringUtils.isNotBlank(userVo.getCommunityName())) {
            criteria.andCommunityNameEqualTo(userVo.getCommunityName());
        }
        if (StringUtils.isNotBlank(userVo.getHouseNumber())) {
            criteria.andHouseNumberEqualTo(userVo.getHouseNumber());
        }

        if (userVo.getIsOfficer() != null) {
            criteria.andIsOfficerEqualTo(userVo.getIsOfficer());
        }
        List<User> userList = userMapper.selectByExample(example);

        List<UserVO> userVOList = userList.stream().map(user -> {
            UserVO userVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(user), UserVO.class);
            Community community = communityServiceAdmin.selectById(userVO.getCommunityId());
            userVO.setStreet(community.getStreet());

            Integer totalTrashIntegral = integralRecordServiceAdmin.sumTrash(userVO.getId());
            Long trashCount = integralRecordServiceAdmin.countTrash(userVO.getId());

            userVO.setTotalTrashIntegral(totalTrashIntegral);
            userVO.setTrashCount(trashCount.intValue());
            return userVO;
        }).collect(Collectors.toList());

        return userVOList;
    }

    public BaseResult officerStatistics() {
        Integer officerUserCount = userMapper.countDemonstrationUser(YesOrNo.YES);
        Integer notOfficerUserCount = userMapper.countDemonstrationUser(YesOrNo.NO);

        Map map = new HashMap();
        map.put("isOfficer", officerUserCount);
        map.put("notOfficer", notOfficerUserCount);

        return BaseResult.ok(map);
    }
}
